// pages/musicSearch/musicSearch.js
import request from '../../utils/request';
import { createSong, getLyric, filterSinger } from '../../utils/song.js';
// 用于防抖
const app = getApp().globalData;
let timer = null;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        placeholderContent: '', //提示的内容
        hotList: [], //热搜榜数组
        searchContent: '', //用户输入的表单数据
        searchList: [], //要匹配（模糊）搜索的关键字
        historyList: [], //搜索历史记录
        songArray: [],
        openNet:true,
        result: false,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        // // 获取初始化的数据
        // this.getInitData();

        // 获取本地历史记录的功能函数
        this.getSearchHistory();
    },

    // 获取初始化的数据
    // async getInitData() {
    //     let placeeholderData = await request('/search/default');
    //     let hotListData = await request('/search/hot/detail');
    //     this.setData({
    //         placeholderContent: placeeholderData.data.showKeyword,
    //         hotList: hotListData.data
    //     });
    // },
    gotSong: function () {//获取歌曲信息
        var that = this;
        wx.request({//微信的request请求
          url: 'https://c.y.qq.com/splcloud/fcgi-bin/gethotkey.fcg?g_tk=5381&jsonpCallback=hotSearchKeysmod_top_search&loginUin=0&hostUin=0&format=jsonp&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq&needNewCode=0',
          success: function (res) {
            let str=res.data+'';
            that.data.songArray = JSON.parse((str).slice((str).indexOf('['),(str).indexOf(']')+1)).slice(0,10);//拼接返回的信息为一个数组
            wx.setStorageSync('songArray', that.data.songArray);//设置本地缓存
            //that.data.songTitleList.push(res.data.data.name);
            // console.log("+++++++++++++++++++++");
            // console.log(res.data.data);
    
            if(that.data.songArray.length==4){//如果爬取到了四首歌曲，就更新songTitleList的值来刷新页面
              that.setData({
                songArray:that.data.songArray
              })
            }
            if(that.data.songArray.length>=8){//分阶段刷新
              that.setData({
                songArray:that.data.songArray
              })
            }
            app.songArray=that.data.songArray
          }
        })
      },
    
      loadIndexSong:function(){//加载第一页显示需要用的歌曲信息,将歌曲获取后放入到data中
        for(var i =0;i<8;i++){
          this.gotSong();
        }
        console.log("have reSetData")
      },
    
      makeSongTitleList:function () {
        var that=this;
        if(this.data.songTitleList.length>=8){
          //只有等全部数据加载完毕之后才会统一显示页面（更新显示数据），大概八首歌的request时间为2s左右
          for(var i=0;i<8;i++){
            console.log(this.data.songTitleList[i]);
          }
          }
    
      },
      // 获取本地历史记录的功能函数
      getSearchHistory() {
         let historyList = wx.getStorageSync('searchHistory')
         historyList = historyList.slice(0,19) //截取数组前20个历史记录
         if (historyList) {
           this.setData({
             historyList
           })
         }
      },

    searchAction: function (event) {
      const keyWrod = event.detail.value || event.currentTarget.dataset.txt
      this.setData({
        searchContent: keyWrod
      })
      if(keyWrod==undefined){
        this.setData({
          result: false
        })
      }else{
      wx.request({
        url: `https://c.y.qq.com/splcloud/fcgi-bin/smartbox_new.fcg?is_xml=0&format=jsonp&key=${keyWrod}g_tk=5381&jsonpCallback=SmartboxKeysCallbackmod_top_search3847&loginUin=0&hostUin=0&format=jsonp&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq&needNewCode=0`,
        data: {
          is_xml: 0,
          format: 'jsonp',
          key: keyWrod,
          g_tk: 5381,
          jsonpCallback: 'SmartboxKeysCallbackmod_top_search3847',
          loginUin: 0,
          hostUin: 0,
          format: 'jsonp',
          inCharset: 'utf8',
          outCharset: 'utf-8',
          notice: 0,
          platform: 'yqq',
          needNewCode: 0
        },
        success: (res) => {
            let res1 = res.data.replace('SmartboxKeysCallbackmod_top_search3847(','')
            let res2 = JSON.parse(res1.substring(0, res1.length -1))
            this.dealData(res2.data)
        },
      })
      let searchContent = this.data.searchContent
      let historyList = this.data.historyList
      if (searchContent && historyList.indexOf(searchContent) === -1) {
        historyList.unshift(searchContent)
      } else {
        if (searchContent) {
          historyList.splice(historyList.indexOf(searchContent), 1)
          historyList.unshift(searchContent)
        }
      }
      this.setData({
        historyList
      })
      // 搜索记录保存到本地
      wx.setStorageSync('searchHistory', historyList)
    }  
    },
    selectSong: function (event) {
      const mid = event.currentTarget.dataset.mid
      wx.request({
        url: `https://c.y.qq.com/v8/fcg-bin/fcg_play_single_song.fcg?songmid=${mid}&tpl=yqq_song_detail&format=jsonp&callback=getOneSongInfoCallback&g_tk=5381&jsonpCallback=getOneSongInfoCallback&loginUin=0&hostUin=0&format=jsonp&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq&needNewCode=0`,
        data: {
          songmid: mid,
        tpl: 'yqq_song_detail',
        format: 'jsonp',
        callback: 'getOneSongInfoCallback',
        g_tk: 5381,
        jsonpCallback: 'getOneSongInfoCallback',
        loginUin: 0,
        hostUin: 0,
        format: 'jsonp',
        inCharset: 'utf8',
        outCharset: 'utf-8',
        notice: 0,
        platform: 'yqq',
        needNewCode: 0
        },
        success: (res) => {
         var res1 = res.data.replace('getOneSongInfoCallback(', '')
        var res2 = JSON.parse(res1.substring(0, res1.length - 1)).data[0]
        let song = {
          id: res2.id,
          mid: mid,
          singer: songs.filterSinger(res2.singer),
          name: res2.name,
          album: res2.album.name,
          duration: res2.interval,
          image: `https://y.gtimg.cn/music/photo_new/T002R300x300M000${res2.album.mid}.jpg?max_age=2592000`,
          musicId: res2.id
        }
        app.songlist = [song]
        // console.log(app.songlist,122222222)
        app.currentIndex = 0
        wx.navigateTo({
          url: '/pages/play/play'
        })
        },
      })
    },
    dealData: function (data) {
      if (data) {
        this.setData({
          result: true
        })
        data.singer ? this.setData({
          singers: data.singer.itemlist
        }) : this.setData({
          singers: []
        })
        data.song ? this.setData({
          songs: data.song.itemlist
        }) : this.setData({
          songs: []
        })
      } else {
        this.setData({
          result: false
        })
      }
    },
    // 清空搜索内容
    clearSearchContent() {
        this.setData({
            searchContent: '',
            searchList: [], //让搜索内容隐藏
            result:false
        })
    },

    // 删除搜索历史记录
    deleteSearchHistory() {
        // 弹框询问用户
        wx.showModal({
            content: '确认删除吗？',
            showCancel: true,
            cancelText: '取消',
            cancelColor: '#000000',
            confirmText: '确定',
            confirmColor: '#3CC51F',
            success: (res) => {
                // console.log(res);
                if (res.confirm) {
                    // 清空data中的 historyList
                    this.setData({
                        historyList: []
                    });
                    // 移除本地的历史记录缓存
                    wx.removeStorageSync('searchHistory');
                }
            },

        });


    },

    // 发请求获取关键字模糊匹配数据
    // async getSearchListData() {
    //     let searchListData = await request('/search', { keywords: this.data.searchContent, limit: 10 })
    //     this.setData({
    //         searchList: searchListData.result.songs
    //     })
    // },


    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {
        if(this.data.openNet==true){
            this.loadIndexSong();
            console.log("onReady");
          }
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {
        var that=this;
        var count=0
        this.setData({
          songArray:[]
        })
        if(this.data.openNet==true){
          this.loadIndexSong();
          console.log("onPullDownRefresh");
        }
        wx.stopPullDownRefresh({
          success: (res) => {},
        })
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})